import axios from "axios";
import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    token: "", // 登录 token
    shppingCarInfo: "", // 购物车信息
    shopCarNum: 0, // 购物车数量
    allChecked: false, // 全选框状态
    content: "全选",
    goodsDet: "", // 商品详情页滚动距离
    userInfo: "", // 保存用户信息
  },
  mutations: {
    // 获取购物车信息
    getshppingCarInfo(state, step) {
      state.shppingCarInfo = step;
    },
    // 单选框点击事件
    shopChecked(state, step) {
      // 改变当前点击状态
      if (state.shppingCarInfo[step].checked) {
        state.shppingCarInfo[step].checked = true;
      } else {
        state.shppingCarInfo[step].checked = false;
      }
      for (let i = 0; i < state.shppingCarInfo.length; i++) {
        if (!state.shppingCarInfo[i].checked) {
          state.allChecked = false;
          state.content = "全选";
          return;
        }
        state.content = "取消全选";
        state.allChecked = true;
      }
    },
    // 全选框点击事件
    allCheckedEle(state) {
      if (state.allChecked) {
        state.allChecked = true;
        state.shppingCarInfo.forEach((item) => {
          item.checked = true;
          state.content = "取消全选";
        });
      } else {
        state.allChecked = false;
        state.shppingCarInfo.forEach((item) => {
          item.checked = false;
          state.content = "全选";
        });
      }
    },
    setAllchecked(state) {
      state.allChecked = false;
    },
    // 商品详情页页面滚动距离
    goodsDet(state, temp) {
      state.goodsDet = temp;
    },
    // 保存用户信息
    setuserInfo(state, info) {
      state.userInfo = info;
    },
  },
  actions: {},
  modules: {},
  getters: {
    // 计算总价
    getPerces(state) {
      let temp = 0;
      if (!state.shppingCarInfo) {
        return;
      }
      state.shppingCarInfo.forEach((item) => {
        if (item.checked) {
          let num = item.count * item.price * 100;
          temp += num;
        }
      });
      return temp;
    },
    // 计算购物车商品数量
    getShopCarNum(state) {
      let temp = 0;
      if (!state.shppingCarInfo) {
        return;
      }
      state.shppingCarInfo.forEach((item) => {
        temp += item.count;
      });
      if (temp <= 99) {
        return temp;
      } else {
        return (temp = "99+");
      }
    },
    // 单选全选
    checkedIsshow(state) {
      // 当全部点亮时，改变全选框的状态
      for (let i = 0; i < state.shppingCarInfo.length; i++) {
        if (!state.shppingCarInfo[i].checked) {
          state.allChecked = false;
          state.content = "全选";
          return;
        }
        state.content = "取消全选";
        state.allChecked = true;
      }
    },
  },
});
